//
//  LinesListController.m
//  NtoccShipper
//
//  Created by 张天兴 on 2023/8/24.
//  Copyright © 2023 zhuchongjin. All rights reserved.
//

#import "LinesListController.h"
#import "ZTXNewLinesCell.h"
#import "ZTXAddLineController.h"
#import "SendLineController.h"
#import "LinesListModel.h"
#import "AddLineItemController.h"

@interface LinesListController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) CJTableView *tableView;
@property (nonatomic, assign) int page;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic,strong) NSString *refreshType; //刷新
@property (nonatomic, strong) UIButton *comitterButton;



@end

@implementation LinesListController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self downRefresh];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitleName:CJLString(@"线路")];
//    [self setRightImage:CJLString(@"新增线路") image:@""];
    [self setBackLeftButton:@""];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZTXNewLinesCell" bundle:nil] forCellReuseIdentifier:@"ZTXNewLinesCell"];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.comitterButton];
    WS(ws);
    self.tableView.placeHolderView = [[KKTableViewNoDataView alloc] initWithFrame:self.tableView.bounds image:[UIImage imageNamed:@"no_data"] viewClick:^{
        [ws.tableView.mj_header beginRefreshing];
    }];
    [self initData];
    [self loadData];
}


- (void)initData{
    self.dataArr = [[NSMutableArray alloc]init];
    self.page = 1;
}

/// <#Description#>
- (void)loadData {
    
    
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/orderProjectRoutes/list",CJBaseUrl);
    NSDictionary *dicPar = @{@"pageNum":CJStringWithFormat(@"%d",self.page),
                             @"pageSize":@"10",
                             @"projectCode":self.projectCode,
                             @"isCancel":@""
    };
    //
    WS(ws);
    [[HDNetworking sharedHDNetworking] GET:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
        
        DLog(@"++++++++%@",responseObject);
        
        NSArray *list = responseObject[@"records"];
        NSString *total = CJStringWithFormat(@"%@",responseObject[@"total"]);
        if ([ws.refreshType isEqualToString:@"down"]) {
            [ws.dataArr removeAllObjects];
        }
        //
        NSError * error ;
        NSArray *arr = [LinesListModel arrayOfModelsFromDictionaries:list error:&error];
        [ws.dataArr addObjectsFromArray:arr];
        
        [ws.tableView.mj_header endRefreshing];
        [ws.tableView.mj_footer endRefreshing];
        
        if (ws.dataArr.count == total.intValue) {
            [ws.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        [ws.tableView reloadData];
    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);
        [ws.tableView.mj_header endRefreshing];
        [ws.tableView.mj_footer endRefreshingWithNoMoreData];
    }];
}

- (void)downRefresh{
    self.refreshType = @"down";
    self.page = 1;
    [self loadData];
}

- (void)upRefresh{
    self.refreshType = @"up";
    self.page ++;
    [self loadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"ZTXNewLinesCell";
    ZTXNewLinesCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    LinesListModel *model = self.dataArr[indexPath.row];
    [cell setCellInfoWithSourceModel:model];
    [cell.stopButton addTarget:self action:@selector(stopButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [cell.deleteButton addTarget:self action:@selector(deleteButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [cell.changeButton addTarget:self action:@selector(changeButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 250;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AddLineItemController *sendVC = [[AddLineItemController alloc] init];
    LinesListModel *model = self.dataArr[indexPath.row];
    sendVC.strOrderCode = model.code;
    [self pushVc:sendVC];
//    SendLineController *sendVC = [[SendLineController alloc] init];
//    [self pushVc:sendVC];
}
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    WS(ws);
    UITableViewRowAction *moRenRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除"handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"" message:@"确定删除该线路？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *updateAct = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
           
        }];
        UIAlertAction *centDateAct = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/orderProjectRoutes/deleteAll",CJBaseUrl);
            LinesListModel *model = self.dataArr[indexPath.row];
            NSDictionary *dicPar = @{@"codes":model.code,
            };
            [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:DeleteType url:strURL parameters:dicPar status:OperationTip success:^(id  _Nonnull responseObject) {
                [ws.dataArr removeObjectAtIndex:indexPath.row];
                [ws.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section]] withRowAnimation:UITableViewRowAnimationFade];
            } failure:^(NSError * _Nonnull error) {
                
            }];
        }];
        [alertC addAction:updateAct];
        [alertC addAction:centDateAct];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertC animated:YES completion:^{
            
        }];
       }];
    NSArray* arr = @[moRenRowAction];
    return arr;
}

- (CJTableView *)tableView{
    if (!_tableView) {
        _tableView = CJTableView.tbInitFrameStyle(CGRectMake(0, CJTableToTopHeight + kTopHeight + 5, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight -CJTableToTopHeight - 50 - SafeAreaBottomHeight - 5),UITableViewStylePlain)
            .tbDelegate(self)
            .tbDataSource(self)
            .tbSetOther(YES)
            .tbEstimatedRowHeight(YES)
            .tbMjHeadFooter(YES)
        ;
        WS(ws);
        _tableView.blockMjHeader = ^(BOOL isheader) {
            if (isheader) {
                [ws downRefresh];
            } else {
                [ws upRefresh];
            }
        };
    }
    [_tableView  setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    return _tableView;
}
- (UIButton *)comitterButton{
    if(!_comitterButton){
        self.comitterButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [self.comitterButton setFrame:CGRectMake(10, self.tableView.bottom + 10, SCREEN_WIDTH - 20, 50)];
        [self.comitterButton setTitle:@"新增线路" forState:(UIControlStateNormal)];
        [self.comitterButton addTarget:self action:@selector(comitterButtonAction) forControlEvents:(UIControlEventTouchUpInside)];
        self.comitterButton.layer.masksToBounds = YES;
        self.comitterButton.layer.cornerRadius = 10;
        self.comitterButton.layer.borderWidth = 1;
        self.comitterButton.layer.borderColor = [UIColor cjMainColor].CGColor;
        [self.comitterButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        self.comitterButton.backgroundColor = [UIColor cjMainColor];
    }
    return _comitterButton;
}
-(void)Rightbuttonclick:(UIButton *)sender{
    ZTXAddLineController *sendVC = [[ZTXAddLineController alloc] init];
    [self pushVc:sendVC];
}
- (void)comitterButtonAction{
    ZTXAddLineController *sendVC = [[ZTXAddLineController alloc] init];
    sendVC.strAddressCityName = self.strAddressCityName;
    sendVC.strDownLoadCityCode = self.strDownLoadCityCode;
    sendVC.strConsigneeLatitude = self.strConsigneeLatitude;
    sendVC.strConsigneeLongitude = self.strConsigneeLongitude;
    sendVC.shipperDetailAddress = self.shipperDetailAddress;
    sendVC.coalBigTypeName = self.coalBigTypeName;
    sendVC.coalBigType = self.coalBigType;
    sendVC.coalType = self.coalType;
    sendVC.coalTypeName = self.coalTypeName;
    sendVC.projectCode = self.projectCode;
    [self pushVc:sendVC];
}
- (void)changeButtonAction:(UIButton *)btn{
    CGPoint point = btn.center;//找到btn中心点记录下来
    point = [self.tableView convertPoint:point fromView:btn.superview];
    NSIndexPath* indexpath = [self.tableView indexPathForRowAtPoint:point];
    LinesListModel *model = self.dataArr[indexpath.row];
    ZTXAddLineController *sendVC = [[ZTXAddLineController alloc] init];
    sendVC.strAddressCityName = self.strAddressCityName;
    sendVC.strDownLoadCityCode = self.strDownLoadCityCode;
    sendVC.strConsigneeLatitude = self.strConsigneeLatitude;
    sendVC.strConsigneeLongitude = self.strConsigneeLongitude;
    sendVC.shipperDetailAddress = self.shipperDetailAddress;
    
    sendVC.coalBigTypeName = self.coalBigTypeName;
    sendVC.coalBigType = self.coalBigType;
    sendVC.coalType = self.coalType;
    sendVC.coalTypeName = self.coalTypeName;
    sendVC.projectCode = self.projectCode;
    
    sendVC.consigneeName = model.consigneeName;
    sendVC.consigneePhone = model.consigneePhone;
    sendVC.consigneeDetailAddress = model.consigneeDetailAddress;
//    sendVC.conUnitCode = model.isTrunk;
    sendVC.price = model.price;
//    sendVC.conUnitName = model.consigneeName;//缺乏先代替
    sendVC.conUnitCode = model.isTrunk;
    sendVC.statTimeStr = model.startTime;//开始时间
    sendVC.endTimeStr = model.endTime;
    sendVC.consigneeAddress = model.consigneeAddress;
    sendVC.consigneeLatitude = model.consigneeLatitude;
    sendVC.consigneeLongitude = model.consigneeLongitude;
    sendVC.consigneeLoadCityCode = model.consigneeSubdivisionCode;//缺地区编码
    sendVC.endType = model.endType;
    sendVC.type = @"1";
    sendVC.ciNumberStr = CJStringWithFormat(@"%d",model.remainTime);
    sendVC.code = model.code;
    [self pushVc:sendVC];
}
- (void)stopButtonAction:(UIButton *)btn{
    CGPoint point = btn.center;//找到btn中心点记录下来
    point = [self.tableView convertPoint:point fromView:btn.superview];
    NSIndexPath *indexpath = [self.tableView indexPathForRowAtPoint:point];
    LinesListModel *model = self.dataArr[indexpath.row];
    if (model.isStop == 1) {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"" message:@"该项目已停用" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *updateAct = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
           
        }];
        [alertC addAction:updateAct];
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertC animated:YES completion:^{
            
        }];
        return;
    }
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/orderProjectRoutes/stop",CJBaseUrl);
    NSDictionary *dicPar = @{@"codes":model.code,
    };
    WS(ws);
    [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:DeleteType url:strURL parameters:dicPar status:OperationTip success:^(id  _Nonnull responseObject) {
        model.isStop = 1;
        [ws.tableView reloadRow:indexpath.row inSection:0 withRowAnimation:(UITableViewRowAnimationFade)];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}
- (void)deleteButtonAction:(UIButton *)btn{
    CGPoint point = btn.center;//找到btn中心点记录下来
    point = [self.tableView convertPoint:point fromView:btn.superview];
    NSIndexPath* indexpath = [self.tableView indexPathForRowAtPoint:point];
    LinesListModel *model = self.dataArr[indexpath.row];
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"" message:@"确定删除该线路？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *updateAct = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       
    }];
    UIAlertAction *centDateAct = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/orderProjectRoutes/delete",CJBaseUrl);
        NSDictionary *dicPar = @{@"codes":model.code,
        };
        WS(ws);
        [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:DeleteType url:strURL parameters:dicPar status:OperationTip success:^(id  _Nonnull responseObject) {
            [ws.dataArr removeObjectAtIndex:indexpath.row];
            [ws.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:indexpath.row inSection:indexpath.section]] withRowAnimation:UITableViewRowAnimationFade];
        } failure:^(NSError * _Nonnull error) {
       }];
    }];
    [alertC addAction:updateAct];
    [alertC addAction:centDateAct];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertC animated:YES completion:^{
        
    }];
}
@end
